package com.zhentao.user.invite;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;

/**
 * @ClassName: InvitationCodeGenerator
 * @Author: 振涛教育_Q
 * @Date: 2024/12/18 9:08
 */
public class InvitationCodeGenerator {
    public static String generateInvitationCode(String phoneNumber) {
        try {
            // 获取当前时间戳（毫秒）与手机号拼接
            long timestamp = Instant.now().toEpochMilli();
            String data = phoneNumber + timestamp;

            // 使用SHA-256算法进行加密处理
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = md.digest(data.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            // 从十六进制字符串结果中选取6位作为邀请码
            // 这里取前6位，你也可以根据需要调整选取规则，比如间隔选取等
            String code = hexString.toString().substring(0, 6).toUpperCase();
            return code;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
